package com.hutao.sso.service.baseInfo_remote;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.hutao.sso.util.ChacheManager;
import com.hutao.sso.util.Constant;
import com.hutao.sso.util.HttpClientUtil;
import com.hutao.sso.util.JsonUtils;
import com.hutao.sso.util.Result;



@Service
public class BasicDataService {

	public Map<String, List<Map<String, Object>>> getBaseInfoMap(String resouceCorePath) {
		Map<String,List<Map<String,Object>>> baseInfoMap=new HashMap<>();
			String userJson = HttpClientUtil.doPost(resouceCorePath);
			if(StringUtils.isNoneEmpty(userJson)){
				Result result=JsonUtils.jsonToPojo(userJson, Result.class);
				if(result.isSuccess()){
					baseInfoMap=(Map<String, List<Map<String, Object>>>) result.getData();
				}
		}
		return baseInfoMap;
	}
	
	
	public String getOfficeCode(String officeName, String configResourceCoreUrl) {
		List<Map<String, Object>> officeList = null;
		String officeCode = null;
		//缓存中存在并且没有过期
		if (ChacheManager.checkCode(Constant.OFFICE_DICTIONARIES, ChacheManager.getCode(Constant.OFFICE_DICTIONARIES))) {
			officeList = ChacheManager.getCode(Constant.OFFICE_DICTIONARIES);
			
			if(officeList == null && officeList.size() == 0) {
				// 科室信息集合
				Map<String, List<Map<String, Object>>> map = getBaseInfoMap(configResourceCoreUrl);
				
				if (map != null) {
					officeList = map.get("offices");
				}
			}
		} else {
			// 科室信息集合
			Map<String, List<Map<String, Object>>> map = getBaseInfoMap(configResourceCoreUrl);
			
			if (map != null) {
				officeList = map.get("offices");
				//把科室信息集合保存到缓存
				ChacheManager.setCode(Constant.OFFICE_DICTIONARIES, officeList);
			}
		}
		
		if(officeList != null && officeList.size() > 0) {
			for (Map<String, Object> map : officeList) {
				if (map.get("name").equals(officeName)) {
					officeCode = map.get("code")!=null?(String)map.get("code"):null;
					break;
				}
			}
		}
		
		return officeCode;
	}
	
	
	

}
